import echarts from 'echarts';

interface IConfig {
  ref: any;
  legend?: {
    data: Array<string> | null
  };
  yAxis: {
    name?: string;
    splitLine?: {
      show: boolean
    }
  },
  xAxis: {
    name?: string;
    splitLine?: {
      show: boolean
    }
  },
  boundaryGap?: boolean;
  label: Array<string>;
  saveImage?: boolean;
  title?: {
    name: string | null
  };
  data: Array<{
    name: string,
    type: string;
    stack?: string | null;
    data: Array<number>;
    color?: string;
    barWidth?: string;
    itemStyle?: any;
    showSymbol?: boolean;
    label?: any;
  }>
}

export function Chart(config: IConfig) {

  const series = {
    showSymbol: true,
    symbol: 'circle',
    barWidth: '20',
  }

  if (config.ref) {
    let myChart = echarts.init(config.ref);
    let option = {
      title: config.title ? {
        ...config.title
      } : null,
      tooltip: {
        trigger: 'axis'
      },
      legend: config.legend ? {
        ...config.legend
      } : null,
      grid: {
        left: '2%',
        right: '8%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: config.saveImage ? {
        feature: {
          saveAsImage: {}
        }
      } : null,
      xAxis: {
        type: 'category',
        boundaryGap: config.boundaryGap || false,
        position: "bottom",
        splitLine: {
          show: false
        },
        axisTick: {
          show: false,
          inside: true
        },
        axisLabel: {
          textStyle: {
            color: '#333'
          }
        },
        ...config.xAxis,
        data: config.label
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: true,
          lineStyle: {
            fontSize: 12
          }
        },
        axisLabel: {
          textStyle: {
            color: '#333'
          }
        },
        barGap: '-100%',
        axisTick: {
          inside: true
        },
        minInterval: 1,
        min: 0,
        ...config.yAxis
      },
      series: Array.isArray(config.data) ? config.data.map(v => ({
        ...series,
        ...v,
      })) : []
    };

    myChart.setOption(option)
  }
}
